package com.padgett.resourcemanagement.service;

import java.io.IOException;
import java.util.Date;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.appengine.labs.repackaged.org.json.JSONObject;
import com.padgett.resourcemanagement.data.ClientDAO;

/**
 * Save client.
 * 
 * @author andyleung
 * 
 */
@SuppressWarnings("serial")
public class AjaxCompleteServiceServlet extends HttpServlet{
	private static final Logger logger=Logger.getLogger(AjaxCompleteServiceServlet.class.getName());
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		String serviceId=req.getParameter("serviceId");
		UserService userService=UserServiceFactory.getUserService();
		User user=userService.getCurrentUser();
		String userEmail=user.getEmail();
		Key key=KeyFactory.stringToKey(serviceId);
		Entity service=ClientDAO.loadEntity(key);
		service.setProperty("LastModifiedBy", userEmail);
		service.setProperty("LastModifiedDate", new Date(System.currentTimeMillis()));
		Date completedDate=new Date(System.currentTimeMillis());
		service.setProperty("CompletedDate", completedDate);
		service.setProperty("Completed", true);
		service.setProperty("CompletedBy", userEmail);
		Key savedKey=ClientDAO.saveEntity(service);
		JSONObject response=new JSONObject();
		try {
			if(savedKey!=null){
				response.put("success", "true");
				response.put("serviceId", KeyFactory.keyToString(savedKey));
			}else{
				response.put("success", "false");
				response.put("error", "Unable to save client at the moment.");
			}
		} catch (JSONException e) {
			logger.severe(e.getMessage());
		}
		resp.getWriter().write(response.toString());
	}

}
